<template>
  <el-dialog :visible.sync="currentShowFlag" append-to-body fullscreen :close-on-click-modal="false" :close-on-press-escape="false" @open="handleDialogOpen" @closed="handleDialogClosed">
    <div slot="title" class="detail-dialog__header">{{$t('system_user.detailDialog')}}</div>
    <div>
      <simple-form ref="form" v-model="formModel" label-width="100px" :form-field="formField" :grid="{xs: 12, sm: 12, md: 8}" :view-flag="viewFlag"></simple-form>
    </div>
    <div slot="footer">
      <el-button @click="handleDialogClose">{{viewFlag ? $t('operation.close') : $t('operation.cancel')}}</el-button>
      <el-button type="primary" @click="handleDataSubmit" v-if="!viewFlag">{{$t('operation.submit')}}</el-button>
    </div>
  </el-dialog>
</template>
<script>
const BASEURL = {
  update: '/Web/SysAdmin/ajax.html?sys_method=Update&sys_objName=V_SYS_UserList&sys_tableName=Sys_User',
  get: '/Web/SysAdmin/ajax.html?sys_method=Get&sys_objName=V_SYS_UserList',
  save: '/Web/SysAdmin/ajax.html?sys_method=Add&sys_objName=V_SYS_UserList&sys_tableName=Sys_User'
}
export default {
  name: 'user-management_detail',
  data () {
    return {
      formModel: { Sex: '1', Status: '1', roleList: [] }
    }
  },
  inject: ['handleDataSearch'],
  computed: {
    currentShowFlag: {
      get () { return this.showFlag },
      set (val) { this.$emit('update:showFlag', val) }
    },

    status () { return this.$getDictList('data_status') },

    formField () {
      return [
        {
          prop: 'UserName',
          label: this.$t('system_user.username'),
          type: 'Input',
          component: { maxlength: 50 },
          rules: { trigger: 'blur', message: this.$t('validate.notBlank'), required: true }
        },
        {
          prop: 'FullName',
          label: this.$t('system_user.fullname'),
          type: 'Input',
          component: { maxlength: 50 },
          rules: { trigger: 'blur', message: this.$t('validate.notBlank'), required: true }
        },
        {
          prop: 'Password',
          label: this.$t('system_user.password'),
          type: 'Input',
          component: { maxlength: 50, placeholder: this.$t('tip.defaultPassword') },
          hidden: this.viewFlag
        },
        {
          prop: 'Sex',
          label: this.$t('system_user.sex'),
          type: 'Select',
          component: {
            optionList: this.$getDictList('性别')
          },
          rules: { trigger: 'change', message: this.$t('validate.notSelect'), required: true }
        },
        {
          prop: 'CompanyID',
          label: this.$t('system_user.companyid'),
          type: 'Select',
          component: {
            optionList: this.extData.orgList.map(item => { return { key: item.value, value: item.value, text: item.text } })
          },
          rules: { trigger: 'change', message: this.$t('validate.notSelect'), required: true }
        },
        {
          prop: 'roleList',
          label: this.$t('system_user.roleids'),
          type: 'Select',
          component: {
            optionList: this.extData.roleList.map(item => { return { key: item.value, value: item.value, text: item.text } }),
            multiple: true
            // valueKey: 'id'
          },
          rules: {
            type: 'array',
            trigger: 'change',
            message: this.$t('validate.notSelect'),
            required: true
          }
        },
        {
          prop: 'PwdExpiredTime',
          label: this.$t('system_user.pwdexpiredtime'),
          type: 'Datepicker',
          component: { valueFormat: 'yyyy-MM-dd HH:mm:ss', type: 'datetime' },
          rules: { trigger: 'blur', message: this.$t('validate.notBlank'), required: true }
        },
        {
          prop: 'Phone',
          label: this.$t('system_user.phone'),
          type: 'Input',
          rules: {
            trigger: 'blur',
            // 添加手机号码格式校验
            validator: (rule, value, callback) => {
              if (/^1[34578]\d{9}$/.test(value) || !value) {
                callback()
              } else {
                callback(new Error('格式校验错误'))
              }
            }
          }
        },
        {
          prop: 'Email',
          label: this.$t('system_user.email'),
          type: 'Input',
          component: { maxlength: 50 },
          rules: {
            trigger: 'blur',
            // 添加手机号码格式校验
            validator: (rule, value, callback) => {
              if (/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value) || !value) {
                callback()
              } else {
                callback(new Error('格式校验错误'))
              }
            }
          }
        },
        {
          prop: 'Status',
          label: this.$t('system_user.status'),
          type: 'Select',
          component: {
            optionList: this.$getDictList('账号状态')
          },
          rules: { trigger: 'change', message: this.$t('validate.notBlank'), required: true }
        },
        {
          prop: 'Memo',
          label: this.$t('system_user.memo'),
          type: 'Input',
          component: { type: 'textarea', maxlength: 75 },
          col: { xs: 24, sm: 24, md: 24 }
        }
      ]
    }
  },
  props: {
    showFlag: { type: Boolean, default: false },
    viewFlag: { type: Boolean },
    detailData: { type: Object },
    extData: { type: Object }
  },
  methods: {
    handleDialogClose () {
      this.currentShowFlag = false
    },

    handleDataSubmit () {
      this.$refs.form.$refs.simpleForm.validate(status => {
        if (status) {
          let loadingFlag = this.$loading({ target: this.$el.querySelector('.el-dialog') })

          let submitModel = this.$_.cloneDeep(this.formModel)
          if (!this.detailData.id && !submitModel.Password) submitModel.Password = '123456'
          submitModel.RoleIDs = submitModel.roleList.join()
          delete submitModel.roleList
          // delete submitModel.lastlogintime
          // delete submitModel.lastloginip
          // delete submitModel.logincount
          Object.assign(submitModel, { sys_mid: this.extData.sys_mid })

          this.$axios
            .post(this.detailData.userid ? BASEURL.update : BASEURL.save, submitModel)
            .then(resp => {
              this.currentShowFlag = false
              this.$message({ type: 'success', message: this.$t('tip.saveSuccess') })
              this.handleDataSearch()
            })
            .finally(() => {
              loadingFlag.close()
            })
        }
      })
    },

    handleDialogOpen () {
      if (!this.detailData.userid) return

      let loadingFlag = this.$loading({ target: this.$el.querySelector('.el-dialog') })
      let params = { id: this.detailData.userid, sys_mid: this.extData.sys_mid }
      this.$axios
        .post(BASEURL.get, params)
        .then(resp => {
          /** 将返回的数据转换为字符串，为了匹配前端字典 */
          resp.Status = resp.Status + ''
          resp.Sex = resp.Sex ? '1' : '0'

          resp.roleList = resp.RoleIDs.split(',')
          this.formModel = resp
        })
        .finally(() => {
          loadingFlag.close()
        })

      // this.$set(this.detailData, `roleList`, this.detailData.roleids.split(','))
      // this.$nextTick(() => { this.$set(this, 'formModel', this.detailData) })
    },
    handleDialogClosed () {
      this.$refs.form.resetFields()
      this.formModel = { Sex: '1', Status: '1', roleList: [] }
    }
  }
}
</script>
